import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import path from 'path';

// 导入服务
import * as modelService from './services/modelService.js';
import * as assessmentService from './services/assessmentService.js';

// 创建Express应用
const app = express();
const PORT = process.env.PORT || 3001;

// 中间件配置
app.use(cors({
  origin: '*', // 在生产环境中应该设置为具体的前端域名
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));
app.use(bodyParser.json({ limit: '10mb' }));
app.use(bodyParser.urlencoded({ extended: true }));

// 静态文件服务
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
app.use(express.static(path.join(__dirname, 'public')));

// 健康检查接口
app.get('/api/health', (req, res) => {
  res.json({
    status: 'healthy',
    timestamp: new Date().toISOString(),
    service: 'employment-assessment-backend'
  });
});

// 模型状态检查接口
app.get('/api/model/status', async (req, res) => {
  try {
    const status = await modelService.checkModelStatus();
    res.json({
      success: true,
      data: status
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// 会话统计接口
app.get('/api/stats', (req, res) => {
  try {
    const stats = modelService.getConversationStats();
    res.json({
      success: true,
      data: stats
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// 初始化评估会话
app.post('/api/assessment/init', (req, res) => {
  try {
    // 生成或使用提供的会话ID
    const conversationId = req.body.conversationId || modelService.generateConversationId();
    
    // 初始化评估
    assessmentService.initializeAssessment(conversationId);
    
    // 获取第一个问题
    const firstQuestion = assessmentService.getFirstQuestion(conversationId);
    
    res.json({
      success: true,
      data: {
        conversationId: conversationId,
        firstQuestion: firstQuestion,
        status: 'initialized'
      }
    });
  } catch (error) {
    console.error('Error initializing assessment:', error);
    res.status(500).json({
      success: false,
      error: '初始化评估失败，请稍后重试'
    });
  }
});

// 处理用户回答
app.post('/api/assessment/answer', async (req, res) => {
  try {
    const { conversationId, answer } = req.body;
    
    if (!conversationId || !answer) {
      return res.status(400).json({
        success: false,
        error: '缺少必要参数: conversationId 和 answer'
      });
    }
    
    // 验证会话存在
    const conversation = modelService.getOrCreateConversation(conversationId);
    
    // 如果是第一个问题，解析行业和职业信息
    if (conversation.isFirstQuestion || !conversation.industry || !conversation.profession) {
      const response = await assessmentService.parseIndustryProfession(conversationId, answer);
      
      // 检查是否解析成功
      if (response.includes('抱歉，我没有理解')) {
        return res.json({
          success: true,
          data: {
            response: response,
            isIndustryProfessionSet: false,
            isRedirect: false
          }
        });
      }
      
      // 解析成功，返回第一个维度的问题
      return res.json({
        success: true,
        data: {
          response: response,
          isIndustryProfessionSet: true,
          isRedirect: false,
          industry: conversation.industry,
          profession: conversation.profession
        }
      });
    }
    
    // 处理用户回答
    const nextResponse = await assessmentService.processAnswer(conversationId, answer);
    
    // 检查是否是重定向
    const isRedirect = nextResponse.includes('谢谢您的分享') || 
                      nextResponse.includes('非常有趣的观点') ||
                      nextResponse.includes('感谢您的回复') ||
                      nextResponse.includes('我理解您的想法');
    
    // 检查是否是评估报告
    const isReport = nextResponse.includes('# 就业成熟度评估报告');
    
    // 获取当前进度
    const progress = assessmentService.getAssessmentProgress(conversationId);
    
    res.json({
      success: true,
      data: {
        response: nextResponse,
        isRedirect: isRedirect,
        isReport: isReport,
        progress: progress,
        isAssessmentCompleted: conversation.isAssessmentCompleted || isReport
      }
    });
  } catch (error) {
    console.error('Error processing answer:', error);
    res.status(500).json({
      success: false,
      error: '处理回答时出错，请稍后重试'
    });
  }
});

// 获取评估进度
app.get('/api/assessment/progress/:conversationId', (req, res) => {
  try {
    const { conversationId } = req.params;
    
    if (!conversationId) {
      return res.status(400).json({
        success: false,
        error: '缺少必要参数: conversationId'
      });
    }
    
    // 获取进度
    const progress = assessmentService.getAssessmentProgress(conversationId);
    
    // 获取会话状态
    const conversation = modelService.getOrCreateConversation(conversationId);
    
    res.json({
      success: true,
      data: {
        progress: progress,
        isAssessmentCompleted: conversation.isAssessmentCompleted,
        industry: conversation.industry,
        profession: conversation.profession
      }
    });
  } catch (error) {
    console.error('Error getting progress:', error);
    res.status(500).json({
      success: false,
      error: '获取进度时出错，请稍后重试'
    });
  }
});

// 获取评估报告
app.get('/api/assessment/report/:conversationId', async (req, res) => {
  try {
    const { conversationId } = req.params;
    
    if (!conversationId) {
      return res.status(400).json({
        success: false,
        error: '缺少必要参数: conversationId'
      });
    }
    
    // 生成报告
    const report = await assessmentService.generateAssessmentReport(conversationId);
    
    // 检查是否是报告
    if (!report.includes('# 就业成熟度评估报告')) {
      return res.status(400).json({
        success: false,
        error: '评估尚未完成，无法生成报告'
      });
    }
    
    res.json({
      success: true,
      data: {
        report: report,
        conversationId: conversationId
      }
    });
  } catch (error) {
    console.error('Error getting report:', error);
    res.status(500).json({
      success: false,
      error: '获取报告时出错，请稍后重试'
    });
  }
});

// 导出评估报告
app.get('/api/assessment/export/:conversationId', (req, res) => {
  try {
    const { conversationId } = req.params;
    const { format } = req.query;
    
    if (!conversationId) {
      return res.status(400).json({
        success: false,
        error: '缺少必要参数: conversationId'
      });
    }
    
    // 导出报告
    const exportResult = assessmentService.exportAssessmentReport(conversationId, format);
    
    if (!exportResult.success) {
      return res.status(400).json({
        success: false,
        error: exportResult.error
      });
    }
    
    // 设置响应头
    const contentType = format === 'json' ? 'application/json' : 'text/plain';
    const fileName = `employment-assessment-report-${conversationId}.${format === 'json' ? 'json' : 'txt'}`;
    
    res.setHeader('Content-Type', contentType);
    res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
    
    res.send(exportResult.content);
  } catch (error) {
    console.error('Error exporting report:', error);
    res.status(500).json({
      success: false,
      error: '导出报告时出错，请稍后重试'
    });
  }
});

// 重置评估会话
app.delete('/api/assessment/reset/:conversationId', (req, res) => {
  try {
    const { conversationId } = req.params;
    
    if (!conversationId) {
      return res.status(400).json({
        success: false,
        error: '缺少必要参数: conversationId'
      });
    }
    
    // 重置会话
    const success = modelService.resetConversation(conversationId);
    
    if (success) {
      res.json({
        success: true,
        message: '评估会话已重置'
      });
    } else {
      res.status(404).json({
        success: false,
        error: '会话不存在'
      });
    }
  } catch (error) {
    console.error('Error resetting conversation:', error);
    res.status(500).json({
      success: false,
      error: '重置会话时出错，请稍后重试'
    });
  }
});

// 获取会话信息
app.get('/api/conversation/:conversationId', (req, res) => {
  try {
    const { conversationId } = req.params;
    
    if (!conversationId) {
      return res.status(400).json({
        success: false,
        error: '缺少必要参数: conversationId'
      });
    }
    
    // 获取会话信息
    const conversation = modelService.getOrCreateConversation(conversationId);
    
    // 返回安全的会话信息（不包含敏感数据）
    res.json({
      success: true,
      data: {
        conversationId: conversation.conversationId,
        industry: conversation.industry,
        profession: conversation.profession,
        isAssessmentCompleted: conversation.isAssessmentCompleted,
        createdAt: conversation.createdAt,
        lastActiveTime: conversation.lastActiveTime,
        hasReport: !!conversation.report
      }
    });
  } catch (error) {
    console.error('Error getting conversation:', error);
    res.status(500).json({
      success: false,
      error: '获取会话信息时出错，请稍后重试'
    });
  }
});

// 处理未知路由
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    error: '接口不存在',
    path: req.path,
    method: req.method
  });
});

// 全局错误处理中间件
app.use((err, req, res, next) => {
  console.error('Unhandled error:', err);
  
  res.status(500).json({
    success: false,
    error: '服务器内部错误',
    message: process.env.NODE_ENV === 'development' ? err.message : undefined
  });
});

// 启动服务器
const server = app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
  console.log(`API文档可访问: http://localhost:${PORT}/api/health`);
  console.log('Press Ctrl+C to stop the server');
});

// 优雅关闭处理
process.on('SIGINT', () => {
  console.log('正在关闭服务器...');
  server.close(() => {
    console.log('服务器已关闭');
    process.exit(0);
  });
});

process.on('SIGTERM', () => {
  console.log('收到终止信号，正在关闭服务器...');
  server.close(() => {
    console.log('服务器已关闭');
    process.exit(0);
  });
});

// 导出app供测试使用
export default app;